exports.handler = function(sid, query, callback) {
    var condition = {};

    if (query.start) {
        var start = new Date(query.start + " 00:00:00");
        condition['mark.day'] = {'$gte':start.getDateNumber()};
    }

    var db = gServers.getGameDB(sid);
    if (!db) {
       callback('db eror'); return;
    }
    
    var uidMap = {}; //{uid, openid}
    async.series([
        function(cb) {
            var platCondition = {};
            if (query.openids) {
                platCondition['_id'] = {'$in':query.openids};  
            }
            if (query.openid) {
                platCondition['_id'] = query.openid;
            }

            var cursor = db.collection('plat').find(platCondition, {});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }

                if (item.uid) {
                    uidMap[item.uid] = item._id;
                }

                if (item.uids) {
                    item.uids.forEach(function(uid) {
                        uidMap[uid] = item._id;
                    });
                }
            });
        },
        function(cb) {
            if (query.openid || query.openids) {
                var uids = Object.keys(uidMap);
                if (uids.length == 0) {
                    cb(); return;
                }
                
                for (var i = 0; i < uids.length; ++i) {
                    uids[i] = +uids[i];
                }

                condition['_id'] = {'$in':uids};
            }

            var cursor = db.collection('user').find(condition, {'mark':1, 'status':1, 'info.un':1});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }
                
                var uid = item._id;
                var openid = uidMap[uid];
                var obj = [uidMap[uid], sid, uid, item.info.un, item.mark.day, item.mark.lastIP, item.status.level, item.status.cash];
                console.log(obj.join('\t')); 
            });
        },
    ], function(err) {
        callback(err); return;
    });;

}

exports.checkQuery = function(query) {
    var start = query.start;
    if (start && start.length != 10) {
        return false;
    }

    return true;
}

exports.help = function() {
    return [
        "[start=yyyy-MM-dd] [openids=file] [openid=xxx]",
        "导出角色信息,最后登录时间>=start",
    ];
}

exports.getTitle = function(query) {
    var title = ['OpenId', 'sid', 'uid', '角色名', '上次登录时间', '上次登录IP', '等级', '剩余元宝'];
    console.log(title.join('\t'));
}
